package com.fcat.common.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fcat.springboot.mybatis.service.impl.TsuantoneBaseServiceImpl;
import com.fcat.base.common.util.ArrayUtil;
import com.fcat.base.common.util.StrUtil;
import com.fcat.common.user.entity.Permission;
import com.fcat.common.user.entity.Role;
import com.fcat.common.user.entity.RolePermission;
import com.fcat.common.user.entity.User;
import com.fcat.common.user.mapper.RoleMapper;
import com.fcat.common.user.service.*;
import com.fcat.common.user.vo.AdminClientRole;
import com.fcat.common.user.vo.UserRoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends TsuantoneBaseServiceImpl<RoleMapper, Role> implements RoleService {

    private final Long defaultRoleGroupId = 1L;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private KeycloakService keycloakService;

    @Value("${token.realm}")
    private String realm;
    @Value("${token.client}")
    private String client;
    @Value("${token.clientSecret}")
    private String clientSecret;
    @Value("${token.clienId}")
    private String clientId;

    @Override
    public List<String> getSystemDefaultRoleName() {
        Map<String, Object> map = new HashMap<>();
        map.put("id", defaultRoleGroupId);
        return mapper.getSystemDefaultRoleName(map);
    }

    @Override
    public List<Long> getSystemDefaultRoleId() {
        Map<String, Object> map = new HashMap<>();
        map.put("id", defaultRoleGroupId);
        return mapper.getSystemDefaultRoleId(map);
    }

    @Override
    @Transactional
    public boolean updateRole(String authorization, Long roleId, List<Long> longs) {
        Integer num = -1;
        //修改数据库
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);
        //首先删除关联关系   不一定之前有绑定所以取返回值没有意义
        rolePermissionService.delete(rolePermission);
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (Long aLong : longs) {
            RolePermission item = new RolePermission();
            item.setPermissionId(aLong);
            item.setRoleId(roleId);
            rolePermissionList.add(item);
        }
        //如果传入进行来的有权限就修改  没有就不修改
        rolePermissionService.insertList(rolePermissionList);
        /*
            1.需要查出所有拥有这个角色的用户,并且查询出所有的权限
            2.删除用户的所有keyloak的web_app的权限
            3.重新查询出所有的权限添加到keycloak
         */
        //查询出来的用户
        List<User> users = userService.getListByRoleId(roleId);
        if (CollectionUtils.isEmpty(users)) return true;
        //获取所有的客户端角色
        for (User user : users) {
            //判断添加了keycloak的就查询出权限信息   确保keycloak里面添加了这条信息
            if (StrUtil.isBlank(user.getKeycloakId())) continue;
            //查询出所有的权限信息然后进行删除
//                    List<AdminClientRole> adminClientRoleList = userService.getAvalableListByClientId(Authorization, clientId, item.getKeycloakId());
            List<AdminClientRole> adminClientRoleList = userService.getListByClientId(authorization, clientId);
            //删除用户的所有权限
            JSONObject jsonObject = keycloakService.deleteRoles(adminClientRoleList,user.getKeycloakId(),clientId, authorization);
            //获取用户的所有权限信息
            List<Permission> permissions = permissionService.getListByUserId(user.getId());
            List<AdminClientRole> addAdminClientRoleList = new ArrayList<>();
            List<String> Strlist = new ArrayList<>();
            //转换成keycloak需要的json数据
            //添加到一个集合里面
            for (Permission permission : permissions) {
                Strlist.add(permission.getName());
            }
            //判断是否有这个权限有这个权限就进行添加
            for (AdminClientRole adminClientRole : adminClientRoleList) {
                if (Strlist.contains(adminClientRole.getName())) {
                    addAdminClientRoleList.add(adminClientRole);
                }
            }
            //添加权限信息
            //添加到keycload
            keycloakService.allocateRoles(addAdminClientRoleList, user.getKeycloakId(), clientId,authorization);
        }
        return true;
    }

    @Override
    public List<Role> getListByUser(Map<String,Object> map) {

        return mapper.getListByUser(map);
    }


    @Override
    public List<Role> getListByCompnayIdAndUsername(Map<String, Object> map) {
        return mapper.getListByCompnayIdAndUsername(map);
    }

    @Override
    public boolean getUserIsAdmin(Map<String, Object> map) {
        List<Long> longs=mapper.getUserIsAdminRole(map);
        return ArrayUtil.isEmpty(longs)?false:longs.contains(Long.valueOf(1));
    }

    @Override
    public List<UserRoleVO> getByCompanyIdAndId(Long companyId, Long id) {
        Map<String,Object> map=new HashMap<>();
        map.put("companyId",companyId);
        map.put("id",id);
        return mapper.getByCompanyIdAndId(map);
    }

    @Override
    public Integer getUserCountByRoleId(Map<String, Object> map) {
        return mapper.getUserCountByRoleId(map);
    }

}